package top.swimmer.tools.collection;

import java.util.Arrays;
import java.util.Collection;

/**
 * Created by xiaoyou on 17-4-28.
 */
public class CollectionUtils {
    public static boolean isEmpty(Collection collection) {
        return collection == null || collection.size() == 0;
    }

    public static void main(String[] args) {
//        int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
        int[] arr = {4, 5, 7, 8, 1, 2, 3, 6};
        quickSort(arr, 0, arr.length - 1);
        System.out.println("排序结果：" + Arrays.toString(arr));
    }

    public static void quickSort(int[] array, int left, int right) {
        if (left < right) {
            dealPivot(array, left, right);
            int pivot = right - 1;
            int i = left;
            int j = right - 1;

            while (true) {
                while (array[++i] < array[pivot]) {}
                while (j > left && array[--j] > array[pivot]) {}
                if (i < j) {
                    swap(array, i, j);
                } else {
                    break;
                }
            }

            if (i < right) {
                swap(array, i, right - 1);
            }
            quickSort(array, left, i - 1);
            quickSort(array, i + 1, right);
        }
    }

    private static void dealPivot(int[] array, int left, int right) {
        int mid = (left + right) / 2;
        if (array[left] > array[mid]) {
            swap(array, left, mid);
        }
        if (array[left] > array[right]) {
            swap(array, left, right);
        }
        if (array[right] < array[mid]) {
            swap(array, right, mid);
        }
        swap(array, right - 1, mid);
    }

    private static void swap(int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}
